package com.caffeine;

import com.github.benmanes.caffeine.cache.*;
import com.google.common.cache.CacheBuilder;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.junit.Test;

import java.util.concurrent.TimeUnit;

public class Demo1 {


    /**
     * Caffeine使用还是非常简单的，如果你用过GuavaCache，
     * 那就更简单了，因为Caffeine的API设计大量借鉴了GuavaCache。
     */
    @Test
    public void test1(){
        Cache<Integer, String> cache = Caffeine.newBuilder()
                //数量上限
                .maximumSize(1024)
                //过期机制
                .expireAfterWrite(5, TimeUnit.MINUTES)
                //弱引用key
                .weakKeys()
                //弱引用value
                .weakValues()
                //剔除监听
                /*.removalListener(new RemovalListener<Integer, String>() {
                    public void onRemoval(@Nullable Integer key, @Nullable String value, @NonNull RemovalCause cause) {
                        System.out.println("key:" + key + ", value:" + value + ", 删除原因:" + cause.toString());
                    }
                })*/
                .removalListener((RemovalListener<Integer, String>) (key, value, cause) ->
                        System.out.println("key:" + key + ", value:" + value + ", 删除原因:" + cause.toString()))
                .build();

                cache.put(1,"laofang");
                cache.put(2,"xiaoliu");
        System.out.println(cache.getIfPresent(1));
        System.out.println(cache.get(1,key->{
            // 本地缓存没有的话，从数据库或者Redis中获取
            //return getValue(key)
            System.out.println(key);
            return "who";
        }));
    }


    /**
     *使用异步加载机制
     */
    @Test
    public void test2(){

        AsyncLoadingCache<Integer, String> asyncLoadingCache = Caffeine.newBuilder()
                .maximumSize(2)
                .expireAfterWrite(5, TimeUnit.MINUTES)
                .refreshAfterWrite(1, TimeUnit.MINUTES)
                .buildAsync(new CacheLoader<Integer, String>() {
                    @Nullable
                    @Override
                    public String load(@NonNull Integer key) throws Exception {
                        //从数据库、远程缓存中获取数据
                        return "123";
                    }
                });

    }
}
